<?php namespace app\api\controller;

use app\api\extend\DataCache;
use think\Config;
use think\Controller;
use think\Db;
use think\Request;

class Rest extends Controller
{
    public $account_id = 0;
    public $user_type  = 'user';
    public $user_id    = 0;
    public $wechat_openid;
    public $token;
    public $auth_state;
    public $token_state;
    public $power_state;
    public $page_num;
    public $page_limit;

    public $data = [
        'code' => 1,
        'msg'  => 'success',
        'data' => [],
    ];

    public function _initialize()
    {
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, auth");
        // 资源类型检测
        $request = Request::instance();
        $header  = $request->header();

        // 基础认证
        $auth = isset($header['auth']) ? $header['auth'] : '';
        if ($auth) {
            $system_auth = DataCache::getAuth();
            if ($auth === $system_auth) {
                $this->auth_state = 1;
            } else {
                $this->auth_state = 401;
            }
        } else {
            $this->auth_state = 401;
        }

        // token授权
        if ($request->isMobile()) {
            // 手机端不刷新token
            $token = isset($header['token']) ? $header['token'] : '';
            if ($token) {
                $check_token = Db::name('tokens')->where(['token' => $token, 'is_mobile' => 1])->find();
                if ($check_token) {
                    $this->account_id    = $check_token['account_id'];
                    $this->wechat_openid = Db::name('accounts')->where(['id' => $check_token['account_id'], 'data_state' => 1])->value('wechat_openid');
                    $this->user_type     = $check_token['user_type'];
                    $this->user_id       = $check_token['user_id'];
                    $this->token         = $token;
                    $this->token_state   = 1;
                } else {
                    $this->token_state = -1;
                }
            } else {
                $this->token_state = -1;
            }
        } else {
            $token = isset($header['token']) ? $header['token'] : '';
            if ($token) {
                $check_token = Db::name('tokens')->where(['token' => $token, 'is_mobile' => 0])->find();
                if ($check_token) {
                    $time_length = time() - $check_token['create_time'];
                    // 时间长度大于1天，重新登录
                    if ($time_length >= 86400) {
                        $this->token_state = -1;
                        // 时间长度大于过期时间（2小时）且小于1天，刷新token
                    } elseif ($time_length < 86400 && $time_length > $check_token['expire_time']) {
                        $this->token_state = -9;
                    } else {
                        $this->account_id    = $check_token['account_id'];
                        $this->wechat_openid = Db::name('accounts')->where(['id' => $check_token['account_id'], 'data_state' => 1])->value('wechat_openid');
                        $this->user_type     = $check_token['user_type'];
                        $this->user_id       = $check_token['user_id'];
                        $this->token         = $token;
                        $this->token_state   = 1;
                    }
                } else {
                    $this->token_state = -1;
                }
            } else {
                $this->token_state = -1;
            }
        }

        // 权限校验
        $uri         = 'uri.' . $request->module() . '/' . $request->controller() . '/' . $request->action();
        $uri_mapping = Config::get($uri);
        $powers      = DataCache::getPowers($this->token);

        // 接口权限测试
        // $this->data['uri']         = $uri;
        // $this->data['uri_mapping'] = $uri_mapping;
        // $this->data['powers']      = $powers;

        if (in_array($uri_mapping, $powers)) {
            $this->power_state = 1;
        } else {
            $this->power_state = 0;
        }

        // 分页信息
        $page_num         = isset($header['page-num']) ? $header['page-num'] : 1;
        $this->page_num   = $page_num;
        $page_limit       = isset($header['page-limit']) ? $header['page-limit'] : 20;
        $this->page_limit = $page_limit;
    }

    /**
     * 【public】权限校验
     *  $check_module值为1,2,3
     *  1为auth认证校验
     *  2为token授权校验
     *  3为api权限校验 = token + api
     *  1 < 2 < 3
     */
    public function check_power($check_module)
    {
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, auth");
        switch ($check_module) {
            case 1:
                if ($this->auth_state != 1) {
                    $this->data['code'] = $this->auth_state;
                    $this->data['msg']  = '认证错误';
                    return 0;
                }
                break;
            case 2:
                if ($this->token_state != 1) {
                    $this->data['code'] = $this->token_state;
                    $this->data['msg']  = '授权错误';
                    return 0;
                }
                break;
            case 3:
                if ($this->token_state != 1) {
                    $this->data['code'] = $this->token_state;
                    $this->data['msg']  = '授权错误';
                    return 0;
                }
                if ($this->power_state != 1) {
                    $this->data['code'] = $this->power_state;
                    $this->data['msg']  = '权限不足';
                    return 0;
                }
                break;
            default:
                $this->data['code'] = 0;
                $this->data['msg']  = '校验模型参数错误';
                return 0;
                break;
        }

        return 1;
    }
}
